package com.leave.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class ProcessDefinitionController {
	
	//注入activitiService服务
	@Autowired
	private RepositoryService repositoryService;
	
	@RequestMapping("/getAllProcessDefinitionByPage")
	@ResponseBody
	public String getAllProcessDefinitionByPage(Integer page,Integer rows) {
		
		Long processCount = repositoryService.createProcessDefinitionQuery().count();
		
		List<ProcessDefinition> pdList = repositoryService.createProcessDefinitionQuery()
											.orderByProcessDefinitionVersion().desc()
											.listPage((page-1)*rows, rows);
		JSONArray jsArr = new JSONArray();
		for(ProcessDefinition pd : pdList) {
			JSONObject js = new JSONObject();
			js.put("id", pd.getId());
			js.put("name", pd.getName());
			js.put("key", pd.getKey());
			js.put("version", pd.getVersion());
			js.put("resourceName", pd.getResourceName());
			js.put("diagramResourceName", pd.getDiagramResourceName());
			js.put("deploymentId", pd.getDeploymentId());
			
			jsArr.add(js);
		}
		JSONObject js = new JSONObject();
		js.put("rows", jsArr);
		js.put("total", processCount);
		return js.toString();
	}
	
	/**
	 *  查看流程图
	 * @param deploymentId
	 * @param diagramResourceName
	 * @param response
	 * @return
	 */
	@RequestMapping("/showView")
	public String viewImage(String deploymentId,String diagramResourceName,HttpServletResponse response){
		InputStream inputStream=repositoryService.getResourceAsStream(deploymentId, diagramResourceName);
        try {
            OutputStream out = response.getOutputStream();
            // 把图片的输入流程写入resp的输出流中
            byte[] b = new byte[1024];
            for (int len = -1; (len= inputStream.read(b))!=-1; ) {
                out.write(b, 0, len);
            }
            // 关闭流
            out.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
	
	
	
	
	
	
	
	
	
	
}


